<template>
  <Main :type="'form'">
    <Title :title="pageName" />
    <el-row>
      <el-col :span="24">
        <el-form ref="form" label-width="120px" :model="form" :rules="form">
          <el-form-item
            label="模板名称"
            prop="name"
            :rules="{ required: true, message: '请输入名称', trigger: 'blur' }"
          >
            <el-input
              v-model="form.name"
              class="form-input"
              size="medium"
              :maxlength="20"
              placeholder="请输入模板名称"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="模板类型"
            prop="type"
            :rules="{ required: true, trigger: 'blur' }"
          >
            <el-radio-group v-model="form.type" @change="empty">
              <el-radio :label="1">买家承担邮费</el-radio>
              <el-radio :label="2">卖家包邮</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            label="计价方式"
            prop="valuation"
            :rules="{ required: true, trigger: 'blur' }"
          >
            <el-radio-group v-model="form.valuation" @change="empty">
              <el-radio :label="1">按件数</el-radio>
              <el-radio :label="2">按重量</el-radio>
              <el-radio :label="3">按体积</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="配送区域及运费">
            <Table :data="form.tableData" style="width:80%;">
              <el-table-column label="可配送区域" width="400">
                <template slot-scope="scope">
                  <div class="addressA">
                    <el-checkbox
                      v-if="scope.$index <= 0"
                      v-model="checked"
                      :disabled="form.tableData.length > 1 && form.type == 2"
                      >{{ scope.row.area_name }}</el-checkbox
                    >
                    <span v-else>{{ scope.row.area_name }}</span>
                  </div>
                  <div v-if="scope.$index > 0" class="addressB">
                    <el-button
                      type="text"
                      @click="editTemplate(scope.row, scope.$index)"
                      >编辑</el-button
                    >
                    <el-button
                      type="text"
                      @click="delTemplate(scope.row.plan_id, scope.$index)"
                      >删除</el-button
                    >
                  </div>

                  <!-- <el-form-item :key='scope.$index'
                                  :prop=''tableData.' + scope.$index + '.area''
                                  :rules='{required: true, message: '可配送区域不能为空', trigger: 'blur'}'>
                      <el-input placeholder='请输入内容'
                                size='small'
                                :disabled='scope.$index==0'
                                v-model='scope.row.area'>
                      </el-input>
                    </el-form-item> -->
                </template>
              </el-table-column>
              <el-table-column :label="labelArr[0]">
                <template slot-scope="scope">
                  <el-form-item
                    :key="scope.$index"
                    :prop="'tableData.' + scope.$index + '.first'"
                    :rules="{
                      required: true,
                      message: '首件不能为空',
                      trigger: 'blur'
                    }"
                  >
                    <el-input-number
                      v-if="form.type == 1"
                      v-model="scope.row.first"
                      size="medium"
                      :min="1"
                      :precision="0"
                      :disabled="scope.$index == 0 && !checked"
                      :controls="false"
                    ></el-input-number>
                    <el-input-number
                      v-else
                      v-model="scope.row.first"
                      size="medium"
                      :min="1"
                      :precision="0"
                      disabled
                      :controls="false"
                    ></el-input-number>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column :label="labelArr[1]">
                <template slot-scope="scope">
                  <el-form-item
                    :key="scope.$index"
                    :prop="'tableData.' + scope.$index + '.first_price'"
                    :rules="{
                      required: true,
                      message: '运费不能为空',
                      trigger: 'blur'
                    }"
                  >
                    <el-input-number
                      v-if="form.type == 1"
                      v-model="scope.row.first_price"
                      size="medium"
                      :min="1"
                      :precision="0"
                      :disabled="scope.$index == 0 && !checked"
                      :controls="false"
                    ></el-input-number>
                    <el-input-number
                      v-else
                      v-model="scope.row.first_price"
                      size="medium"
                      :min="1"
                      :precision="0"
                      disabled
                      :controls="false"
                    ></el-input-number>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column :label="labelArr[2]">
                <template slot-scope="scope">
                  <el-form-item
                    :key="scope.$index"
                    :prop="'tableData.' + scope.$index + '.continuation'"
                    :rules="{
                      required: true,
                      message: '续件不能为空',
                      trigger: 'blur'
                    }"
                  >
                    <el-input-number
                      v-if="form.type == 1"
                      v-model="scope.row.continuation"
                      size="medium"
                      :min="1"
                      :precision="0"
                      :disabled="scope.$index == 0 && !checked"
                      :controls="false"
                    ></el-input-number>
                    <el-input-number
                      v-else
                      v-model="scope.row.continuation"
                      size="medium"
                      :min="1"
                      :precision="0"
                      disabled
                      :controls="false"
                    ></el-input-number>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column :label="labelArr[3]">
                <template slot-scope="scope">
                  <el-form-item
                    :key="scope.$index"
                    :prop="'tableData.' + scope.$index + '.continuation_price'"
                    :rules="{
                      required: true,
                      message: '续费不能为空',
                      trigger: 'blur'
                    }"
                  >
                    <el-input-number
                      v-if="form.type == 1"
                      v-model="scope.row.continuation_price"
                      size="medium"
                      :min="0"
                      :precision="2"
                      :disabled="scope.$index == 0 && !checked"
                      :controls="false"
                    ></el-input-number>
                    <el-input-number
                      v-else
                      v-model="scope.row.continuation_price"
                      size="medium"
                      :min="0"
                      :precision="2"
                      disabled
                      :controls="false"
                    ></el-input-number>
                  </el-form-item>
                </template>
              </el-table-column>

              <!-- <el-table-column label='操作'
                                 width='80px'>
                  <template slot-scope='scope'>
                    <el-button type='text'
                               v-if='scope.$index>0'
                               @click='delTemplate(scope.$index)'>删除</el-button>
                  </template>
                </el-table-column> -->
            </Table>
            <div
              style="margin-top:10px;font-size:12px;"
              class="add-form-hintColor"
            >
              <el-button
                :disabled="checked && form.type == 2"
                plain
                @click="addTemplate"
                >点击添加可配送区域</el-button
              >
              &emsp;
            </div>
          </el-form-item>
          <el-form-item>
            <el-checkbox v-model="form.is_default"
              >设为新商品默认模板（新添加的商品支持商家配送时的默认模板）</el-checkbox
            >
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
    <Footer>
      <el-button plain @click="$emit('out')">取 消</el-button>
      <el-button type="primary" @click="submit">保 存</el-button>
    </Footer>
    <linkage
      :dialog="dialog"
      :data-json="dataJson"
      :filter-arr="filterArr"
      @dialogShow="dialogShow"
    />
  </Main>
</template>
<script>
import { SETDISTRIBUTIONTEMPLETE } from "../../service";
import { DELDISTRIBUTIONPLAN } from "@/service/public";

var _ = require("lodash");

export default {
  components: {
    linkage: r =>
      require.ensure([], () => r(require("publicCom/linkages")), "linkages")
  },
  props: {
    dataMsg: {
      default: () => {},
      type: Object
    }
  },
  data() {
    return {
      pageName: "运费模板-新建运费",
      form: {
        name: "",
        type: 1,
        valuation: 1,
        tableData: [
          {
            areaJson: "",
            area_name: "所有区域默认配送",
            first: 1,
            first_price: 0,
            continuation: 1,
            continuation_price: 0,
            plan_id: ""
          }
        ],
        is_default: false
      },
      dialog: false,
      checked: true,
      dataJson: "",
      arrIndex: -1,
      labelArr: ["首件（个）", "运费（元）", "续件（个）", "续费（元）"],
      filterArr: [],
      templete_id: "",
      status: false
    };
  },
  watch: {
    "form.valuation"(v) {
      switch (v) {
        case 1:
          this.labelArr = [
            "首件（个）",
            "运费（元）",
            "续件（个）",
            "续费（元）"
          ];
          break;
        case 2:
          this.labelArr = [
            "首重（kg）",
            "运费（元）",
            "续重（kg）",
            "续费（元）"
          ];
          break;
        case 3:
          this.labelArr = [
            "首体积（m³）",
            "运费（元）",
            "续体积（m³）",
            "续费（元）"
          ];
          break;
      }
    }
  },
  created() {
    if (JSON.stringify(this.dataMsg) !== "{}") {
      this.pageName = "运费模板-編輯运费";
      this.form.name = this.dataMsg.name;
      this.form.type = this.dataMsg.type;
      this.form.valuation = this.dataMsg.valuation;
      this.form.is_default = this.dataMsg.is_default === 1;
      this.form.tableData = this.dataMsg.disarea;
      if (!this.dataMsg.planJson) {
        this.form.tableData.unshift({
          areaJson: "",
          area_name: "所有区域默认配送",
          first: 1,
          first_price: 0,
          continuation: 1,
          continuation_price: 0,
          plan_id: ""
        });
        this.checked = false;
      }
      this.form.tableData.forEach(ele => {
        if (ele.areaJson) {
          ele.areaJson = JSON.parse(ele.areaJson);
          for (let key in ele.areaJson) {
            this.filterArr.push(key);
          }
          ele.areaJson = JSON.stringify(ele.areaJson);
        }
      });
      this.templete_id = this.dataMsg.templete_id;
    } else {
      this.pageName = "运费模板-新建运费";
      this.form.name = "";
      this.form.type = 1;
      this.form.valuation = 1;
      this.form.is_default = false;
      this.form.tableData = [];
      this.form.tableData.push({
        areaJson: "",
        area_name: "所有区域默认配送",
        first: 1,
        first_price: 0,
        continuation: 1,
        continuation_price: 0,
        plan_id: ""
      });
    }
  },
  methods: {
    empty() {
      this.$confirm("您设置的可配送区域及运费设置将全部清空！", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.status = true;
        this.form.tableData = [];
        this.filterArr = [];
        this.form.tableData.push({
          areaJson: "",
          area_name: "所有区域默认配送",
          first: 1,
          first_price: 0,
          continuation: 1,
          continuation_price: 0,
          plan_id: ""
        });
      });
    },
    editTemplate(e, i) {
      this.arrIndex = i;
      this.dialog = true;
      this.dataJson = e;
    },
    addTemplate() {
      if (this.form.tableData.length > 1) {
        let lock = this.form.tableData[this.form.tableData.length - 1];
        if (!lock.plan_id) {
          this.$message.error("请选择可配送区域");
          return false;
        }
      }
      this.form.tableData.push({
        areaJson: "",
        area_name: "请选择可配送区域",
        first: 1,
        first_price: 0,
        continuation: 1,
        continuation_price: 0,
        plan_id: ""
      });
    },
    delTemplate(planId, i) {
      this.form.tableData.splice(i, 1);
      DELDISTRIBUTIONPLAN({ plan_id_arr: planId });
    },

    submit() {
      let arr = _.cloneDeep(this.form.tableData);
      arr.splice(0, 1);
      arr.forEach(ele => {
        ele.area_name = "";
        ele.areaJson = "";
      });
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (JSON.stringify(this.dataMsg) !== "{}" && this.status) {
            let planIdArr = [];
            this.dataMsg.disarea.forEach(ele => {
              planIdArr.push(ele.plan_id);
            });
            DELDISTRIBUTIONPLAN({ plan_id_arr: planIdArr.join(",") }).then(
              res => {
                let { code } = res;
                if (code === 200) {
                  this.status = false;
                }
              }
            );
          }

          SETDISTRIBUTIONTEMPLETE({
            flag: "save",
            name: this.form.name,
            type: this.form.type,
            valuation: this.form.valuation,
            is_default: this.form.is_default ? 1 : 0,
            planJson: this.checked ? this.form.tableData[0] : "",
            areaJson: arr,
            templete_id: this.templete_id
          }).then(res => {
            let { code, msg } = res;
            if (code === 200) {
              this.$message.success(msg);
              this.$emit("out");
            } else {
              this.$message.error(msg);
            }
          });
        }
      });
    },
    dialogShow(e) {
      this.dialog = false;
      if (e) {
        this.form.tableData[this.arrIndex].areaJson = e.areaJson;
        let jsonArr = JSON.parse(e.areaJson);

        for (let key in jsonArr) {
          this.filterArr.push(key);
        }

        this.form.tableData[this.arrIndex].area_name = e.area_name;
        this.form.tableData[this.arrIndex].plan_id = e.plan_id;
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.addressA {
  width: 80%;
  float: left;
}
.addressB {
  width: 20%;
  float: right;
}
</style>
